/* =============================================================
 * tool_tip.js v1.1.0
 * =============================================================
 * Original written by Ysy
 * =============================================================
 * Date 04/29/2021
 * ============================================================ */


(function (factory) {
    "use strict";
    if (typeof define === "function" && define.amd) {
        define(["jquery"], factory);
    } else {
        factory(jQuery);
    }
}(function ($) {

    let ToolTip = function (element, options) {
        this.options = $.extend({}, $.fn.toolTip.defaults, options);
        this.$element = $(element);
        this.$tip = $(this.options.tip);
        this.source = this.options.source;
        this.enter = false;
        this.listen();
    };

    ToolTip.prototype = {

        constructor: ToolTip,

        render: function () {// 渲染
            // 显示内容
            this.displayText();
            // 加载元素
            this.$element.after(this.$tip);
            // 主题
            this.$tip.addClass(this.options.theme);
            // 定位
            this.position();
            this.show();
        },

        position: function () {
            this.$tip.attr("x-placement", this.options.position);
        },

        displayText: function () {// 显示文本
            let text = this.source.join("<br>");
            this.$tip.find("div.tool_tip_content").html(text);
        },

        show: function () {
            this.$tip.fadeIn(350);
        },

        hide: function () {
            this.$tip.fadeOut(100);
            this.destroy();
        },

        destroy: function () {
            this.$tip.detach();
        },

        init: function (data) {
            this.source = data;
            this.render();
        },

        listen: function () {
            this.$element
                .on("mouseenter", $.proxy(this.mouseEnter, this))
            .on("mouseleave", $.proxy(this.mouseLeave, this));
        },

        mouseEnter: function () {
            if ($.isFunction(this.source)) {
                this.source($.proxy(this.process, this));
            } else if (this.source) {
                this.init(this.source);
            }
        },

        mouseLeave: function () {
            this.hide();
        },

        process: function (data) {
            this.init(data);
        },
    };

    let old = $.fn.toolTip;

    $.fn.toolTip = function (options) {
        return new ToolTip(this, options);
    };

    $.fn.toolTip.defaults = {
        tip: "<div class='tool_tip_wrapper'>" +
        "    <div class='tool_tip_arrow'></div>" +
        "    <div class='tool_tip_content'></div>" +
        "</div>",
        source: [],
        position: "bottom", // top right left bottom
        theme: "dark", // light dark
    };

    $.fn.toolTip.Constructor = ToolTip;

    $.fn.toolTip.noConflict = function () {
        $.fn.toolTip = old;
        return this;
    };
}));
